package com.zkjd.lingdong.bluetooth

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.ParcelUuid
import androidx.core.app.ActivityCompat
import com.zkjd.lingdong.repository.SettingsRepository
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import timber.log.Timber
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.experimental.and

internal const val TAG = "BleManagerImpl"
private const val CONNECTION_TIMEOUT_MS = 10000L // 连接超时时间，10秒

/**
 * 延迟发送，首次连接蓝牙，需要延迟发送数据才能成功
 */
private const val DELAY_SEND= 1000L

/**
 * 等待鉴权响应，设置5秒超时
 */
private const val WAIT_TO=5000L

/**
 * 带超时保护,保护写入和下发
 */
private const val DELAY_TIMEOUT=3000L
/**
 * 蓝牙管理器实现类，提供BLE设备的扫描、连接、通信等功能
 */
@Singleton
class BleManagerImpl @Inject constructor(
    @ApplicationContext private val appContext: Context,
    private val settingsRepository: SettingsRepository
) : BleManager {

    /** 用于后台任务的协程作用域 */
    private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    /** 蓝牙管理器和适配器 */
    private lateinit var bluetoothManager: BluetoothManager
    private lateinit var bluetoothAdapter: BluetoothAdapter

    /** 存储设备地址到GATT连接的映射 */
    private val deviceGattMap = ConcurrentHashMap<String, BluetoothGatt>()

    /** 扫描状态流 */
    private val scanStateFlow = MutableStateFlow<ScanState>(ScanState.NotScanning)

    /** 扫描状态流2 */
    private val scanStateFlow2 = MutableStateFlow<ScanState>(ScanState.NotScanning)
    
    /** 设备事件流 */
    private val deviceEventsFlow = MutableSharedFlow<DeviceEvent>(replay = 0)

    /** 扫描结果列表 */
    private val scanResults = mutableListOf<BluetoothDevice>()

    /** 扫描结果列表2 */
    private val scanResults2 = mutableListOf<BluetoothDevice>()

    /** 存储连接操作的异步结果 */
    private val connectionResults = ConcurrentHashMap<String, CompletableDeferred<Boolean>>()

    /** 存储写入特征回调结果 */
    private val writeCallbacks = ConcurrentHashMap<String, CompletableDeferred<Boolean>>()

    /** 存储已成功连接并发现服务的设备信息 */
    private val discoveredServicesCache = ConcurrentHashMap<String, Boolean>()
    
    /** 存储设备特征信息 */
    private val deviceCharacteristics = ConcurrentHashMap<String, Map<UUID, BluetoothGattCharacteristic>>()

    /** 存储鉴权信息 */
    private val authenticationData = ConcurrentHashMap<String, AuthData>()
    
    /** 鉴权结果回调 */
    private val authenticationResults = ConcurrentHashMap<String, CompletableDeferred<Boolean>>()

    /** 用于同步处理蓝牙特性变化事件的互斥锁 */
    private val characteristicChangedLock = Any()
    
    /** 记录最近处理的通知特征值哈希，用于防止重复处理 */
    private val lastProcessedNotification = ConcurrentHashMap<String, Long>()

    /**
     * 初始化蓝牙管理器
     * @param context 应用上下文
     */
    override fun initialize(context: Context) {
        bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothAdapter = bluetoothManager.adapter
    }

    /**
     * 开始扫描BLE设备
     * 扫描结果通过 scanStateFlow 流发布
     */
    override fun startScan() {
        // 检查蓝牙是否启用
        if (!bluetoothAdapter.isEnabled) {
            scanStateFlow.tryEmit(ScanState.ScanFailed("蓝牙未启用"))
            return
        }

        // 检查蓝牙扫描权限
        if (!hasBluetoothPermission("scan")) {
            scanStateFlow.tryEmit(ScanState.ScanFailed("缺少蓝牙扫描权限"))
            return
        }

        // 检查位置权限
        if (ActivityCompat.checkSelfPermission(
                appContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            scanStateFlow.tryEmit(ScanState.ScanFailed("缺少位置权限，无法扫描设备"))
            return
        }

        // 清空之前的扫描结果
        scanResults.clear()
        scanStateFlow.tryEmit(ScanState.Scanning)

        // 设置扫描参数 - 低延迟模式提高扫描速度
        val scanSettings = ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build()

        val filters = mutableListOf<ScanFilter>()
        // 创建MAC地址过滤器
        val scanFilter: ScanFilter = ScanFilter.Builder()
            .setServiceUuid(ParcelUuid.fromString("0000ffd0-0000-1000-8000-00805f9b34fb")) // 替换为目标设备的MAC地址
            .build()
        // 将过滤器添加到列表
        filters.add(scanFilter)

        // 开始扫描
        try {
            bluetoothAdapter.bluetoothLeScanner.startScan(
                null, // 不使用过滤器，在回调中根据设备名称前缀筛选
                scanSettings,
                scanCallback
            )
            Timber.tag(TAG).w("开始扫描BLE设备")
        } catch (e: Exception) {
            scanStateFlow.tryEmit(ScanState.ScanFailed("扫描启动失败: ${e.message}"))
            Timber.tag(TAG).e(e, "启动扫描失败")
        }
    }

    /**
     * 开始扫描BLE设备
     * 扫描结果通过 scanStateFlow 流发布
     */
    override fun startScan2(macAddress: String) {
        // 检查蓝牙是否启用
        if (!bluetoothAdapter.isEnabled) {
            scanStateFlow2.tryEmit(ScanState.ScanFailed("蓝牙未启用"))
            return
        }

        // 检查蓝牙扫描权限
        if (!hasBluetoothPermission("scan")) {
            scanStateFlow2.tryEmit(ScanState.ScanFailed("缺少蓝牙扫描权限"))
            return
        }

        // 检查位置权限
        if (ActivityCompat.checkSelfPermission(
                appContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            scanStateFlow2.tryEmit(ScanState.ScanFailed("缺少位置权限，无法扫描设备"))
            return
        }

        // 清空之前的扫描结果
        scanResults2.clear()
        scanStateFlow2.tryEmit(ScanState.Scanning)


        // 创建MAC地址过滤器
        val scanFilter: ScanFilter = ScanFilter.Builder()
            .setDeviceAddress(macAddress) // 替换为目标设备的MAC地址
            .build()


        // 将过滤器添加到列表
        val filters = mutableListOf(scanFilter)


        // 设置扫描参数 - 低延迟模式提高扫描速度
        val scanSettings = ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build()

        // 开始扫描
        try {
            bluetoothAdapter.bluetoothLeScanner.startScan(
                null, // 不使用过滤器，在回调中根据设备名称前缀筛选
                scanSettings,
                scanCallback2
            )
            Timber.tag(TAG).w("开始扫描BLE设备2")
        } catch (e: Exception) {
            scanStateFlow2.tryEmit(ScanState.ScanFailed("扫描启动失败2: ${e.message}"))
            Timber.tag(TAG).e(e, "启动扫描失败2")
        }
    }

    /**
     * 开始扫描BLE设备
     * 扫描结果通过 scanStateFlow 流发布
     */
    override fun startScan3(filters: MutableList<ScanFilter>) {
        // 检查蓝牙是否启用
        if (!bluetoothAdapter.isEnabled) {
            scanStateFlow2.tryEmit(ScanState.ScanFailed("蓝牙未启用"))
            return
        }

        // 检查蓝牙扫描权限
        if (!hasBluetoothPermission("scan")) {
            scanStateFlow2.tryEmit(ScanState.ScanFailed("缺少蓝牙扫描权限"))
            return
        }

        // 检查位置权限
        if (ActivityCompat.checkSelfPermission(
                appContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            scanStateFlow2.tryEmit(ScanState.ScanFailed("缺少位置权限，无法扫描设备"))
            return
        }

        // 清空之前的扫描结果
        scanResults2.clear()
        scanStateFlow2.tryEmit(ScanState.Scanning)


        // 设置扫描参数 - 低延迟模式提高扫描速度
        val scanSettings = ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build()

        // 开始扫描
        try {
            bluetoothAdapter.bluetoothLeScanner.startScan(
                filters, // 不使用过滤器，在回调中根据设备名称前缀筛选
                scanSettings,
                scanCallback2
            )
            Timber.tag(TAG).w("开始扫描BLE设备2")
        } catch (e: Exception) {
            scanStateFlow2.tryEmit(ScanState.ScanFailed("扫描启动失败2: ${e.message}"))
            Timber.tag(TAG).e(e, "启动扫描失败2")
        }
    }


    /**
     * 停止BLE设备扫描
     */
    override fun stopScan() {
        try {
            bluetoothAdapter.bluetoothLeScanner?.stopScan(scanCallback)
            scanStateFlow.tryEmit(ScanState.NotScanning)
            Timber.tag(TAG).w("停止扫描BLE设备")
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "停止扫描失败")
        }
    }

    /**
     * 停止BLE设备扫描
     */
    override fun stopScan2() {
        try {
            bluetoothAdapter.bluetoothLeScanner?.stopScan(scanCallback2)
            scanStateFlow2.tryEmit(ScanState.NotScanning)
            Timber.tag(TAG).w("停止扫描BLE设备2")
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "停止扫描失败2")
        }
    }

    /**
     * 获取当前的扫描状态流
     * @return 扫描状态流
     */
    override fun getScanState(): Flow<ScanState> = scanStateFlow.asStateFlow()

    override fun getScanState2(): Flow<ScanState> = scanStateFlow2.asStateFlow()

    /**
     * 连接到BLE设备
     * @param device 要连接的蓝牙设备
     * @return 连接成功返回true，否则返回false
     */
    override suspend fun connect(device: BluetoothDevice): Boolean = withContext(Dispatchers.IO) {
        // 检查蓝牙连接权限
        if (!hasBluetoothPermission()) {
            deviceEventsFlow.emit(DeviceEvent.ConnectionFailed(device, "缺少蓝牙连接权限"))
            Timber.tag(TAG).e("连接失败: 缺少蓝牙连接权限")
            return@withContext false
        }

        try {
            //这里影响到鉴权
            //if (connectionResults[device.address]!=null){
            //    return@withContext true
            //}
            // 如果已存在连接，先断开
            disconnectExistingConnection(device.address)

            // 创建连接结果的异步通知器
            val connectResult = CompletableDeferred<Boolean>()
            connectionResults[device.address] = connectResult

            // 判断是否是重连
            val isReconnecting = discoveredServicesCache[device.address] == true
            
            // 重连场景使用autoConnect=true可能导致连接延迟，这里统一使用false以保证低延迟
            val autoConnect = false

            // 创建新连接
            Timber.tag(TAG).w("尝试${if(isReconnecting) "重新" else ""}连接设备: ${device.address}, autoConnect=$autoConnect")
            val gatt = device.connectGatt(appContext, autoConnect, gattCallback)
            deviceGattMap[device.address] = gatt

            true

        } catch (e: Exception) {
            deviceEventsFlow.emit(DeviceEvent.ConnectionFailed(device, "连接失败: ${e.message}"))
            Timber.tag(TAG).e(e, "连接过程中发生异常: ${device.address}")
            return@withContext false
        }
    }

    /**
     * 断开与BLE设备的连接
     * @param device 要断开的蓝牙设备
     * @return 断开成功返回true，否则返回false
     */
    override suspend fun disconnect(device: BluetoothDevice) = withContext(Dispatchers.IO) {
        if (!hasBluetoothPermission()) {
            Timber.tag(TAG).e("断开连接失败: 缺少蓝牙连接权限")
            return@withContext false
        }

        val gatt = deviceGattMap[device.address] ?: run {
            Timber.tag(TAG).w("找不到设备的GATT连接: ${device.address}")
            return@withContext false
        }

        try {
            Timber.tag(TAG).w("断开设备连接: ${device.address}")
            gatt.disconnect()
            return@withContext true
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "断开连接失败: ${device.address}")
            return@withContext false
        }
    }

    /**
     * 获取设备事件流
     * @return 设备事件共享流
     */
    override fun getDeviceEvents(): SharedFlow<DeviceEvent> = deviceEventsFlow

    /**
     * 关闭蓝牙管理器，释放资源
     */
    override fun close() {
        // 停止扫描
        stopScan()

        // 断开所有设备连接
        for (gatt in deviceGattMap.values) {
            closeGattConnection(gatt)
        }

        deviceGattMap.clear()
        connectionResults.clear()
        writeCallbacks.clear()
        discoveredServicesCache.clear()
        deviceCharacteristics.clear()
        authenticationData.clear()
        authenticationResults.clear()
        lastProcessedNotification.clear()
        Timber.tag(TAG).w("蓝牙管理器已关闭")
    }

    /**
     * BLE设备扫描回调
     */
    private val scanCallback = object : ScanCallback() {
        /**
         * 收到单个扫描结果
         */
        @SuppressLint("NewApi")
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            val device = result.device
            // 只处理名称匹配的设备
            if (device.name != null && device.name.startsWith(BleConstants.DEVICE_NAME_HEAD)) {
                Timber.tag(TAG).w("扫描到设备：${device.address}, 名称=${device.name}, RSSI=${result.rssi}")
                //读取广播内容，判断是否配对广播
                try {

                    //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                        //val advertisingDataMap = result.scanRecord?.advertisingDataMap

                        // 保存RSSI值用于距离判断
                        result.rssi.let { rssi ->
                            device.setRssiValue(rssi)
                        }
                        val dataGB=result.scanRecord?.bytes
                        val dataGBString=BleAuthUtils.byteArrayToHexString(dataGB!!)
                        Timber.tag(TAG).e("广播=${dataGBString}")

//                        if(device.name.startsWith(BleConstants.LYT)){
//
//                        }else if(device.name.startsWith(BleConstants.GR)){
//
//                        }


                        //1为配对广播，2为重连广播
//                        val value = advertisingDataMap?.getValue(255)
//                        val valueString = value?.let { BleAuthUtils.byteArrayToHexString(it) }
                        var valueString=dataGBString.substring(10,12)
                        if (valueString != null) {
                            if (valueString.toInt() == 1) {
                                scanResults.add(device)
                                scanStateFlow.tryEmit(ScanState.ScanResult(scanResults.toList()))
                            }
                        }
//                    }else{
//                        // 保存RSSI值用于距离判断
//                        result.rssi.let { rssi ->
//                            device.setRssiValue(rssi)
//                        }
//                        scanResults.add(device)
//                        scanStateFlow.tryEmit(ScanState.ScanResult(scanResults.toList()))
//
//                    }
                } catch (e: Exception) {
                    Timber.tag(TAG).w("广播没有FF")
                }
            }
        }

        /**
         * 收到批量扫描结果
         */
        override fun onBatchScanResults(results: MutableList<ScanResult>) {
            Timber.tag(TAG).w("收到批量扫描结果: ${results.size}个")
            for (result in results) {
                onScanResult(0, result)
            }
        }

        /**
         * 扫描失败
         */
        override fun onScanFailed(errorCode: Int) {
            Timber.tag(TAG).e("扫描失败, 错误码: $errorCode")

            stopScan()

            scanStateFlow.tryEmit(ScanState.ScanFailed("扫描失败，错误码: $errorCode"))
        }

    }



    /**
     * BLE设备扫描回调
     */
    private val scanCallback2 = object : ScanCallback() {
        /**
         * 收到单个扫描结果
         */
        @SuppressLint("NewApi")
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            val device = result.device
            // 只处理名称匹配的设备
            Timber.tag(TAG).w("扫描到设备2一直在")
            if (device.name != null && device.name.startsWith(BleConstants.DEVICE_NAME_HEAD)) {
                Timber.tag(TAG).w("扫描到需要重连的设备：${device.address}, 名称=${device.name}, RSSI=${result.rssi}")


               // addDeviceIfNotExists(device)

//                try {
//
//                    // 如果已存在连接，先断开
//                    disconnectExistingConnection(device.address)
//
//                    // 创建连接结果的异步通知器
//                    val connectResult = CompletableDeferred<Boolean>()
//                    connectionResults[device.address] = connectResult
//
//                    // 判断是否是重连
//                    val isReconnecting = discoveredServicesCache[device.address] == true
//
//                    // 重连场景使用autoConnect=true可能导致连接延迟，这里统一使用false以保证低延迟
//                    val autoConnect = false
//
//                    // 创建新连接
//                    Timber.tag(TAG).w("尝试${if(isReconnecting) "重新" else ""}连接设备: ${device.address}, autoConnect=$autoConnect")
//                    val gatt = device.connectGatt(appContext, autoConnect, gattCallback)
//                    deviceGattMap[device.address] = gatt
//
//
//                } catch (e: Exception) {
//
//                    Timber.tag(TAG).e(e, "连接过程中发生异常: ${device.address}")
//
//                }
//                stopScan2()
            }

        }

        /**
         * 收到批量扫描结果
         */
        override fun onBatchScanResults(results: MutableList<ScanResult>) {
            Timber.tag(TAG).w("收到批量扫描结果: ${results.size}个")
            for (result in results) {
                onScanResult(0, result)
            }
        }

        /**
         * 扫描失败
         */
        override fun onScanFailed(errorCode: Int) {
            Timber.tag(TAG).e("扫描失败, 错误码: $errorCode")

            stopScan2()

            scanStateFlow2.tryEmit(ScanState.ScanFailed("扫描失败，错误码: $errorCode"))
        }

    }


    // 添加设备时进行去重判断
    fun addDeviceIfNotExists(newDevice: BluetoothDevice) {
        // 检查列表中是否已存在相同MAC地址的设备
        val isExists = scanResults2.any { it.address == newDevice.address }
        if (!isExists) {
            scanResults2.add(newDevice)
            scanStateFlow2.tryEmit(ScanState.ScanResult(scanResults2.toList()))
            Timber.tag(TAG).e("重新搜索添加的："+newDevice.name)
        }
    }

    // 根据指定的address移除设备
    override fun removeDeviceByAddress(targetAddress: String) {
        // 遍历列表，移除所有address匹配的设备（实际只会有一个）
        scanResults2.removeAll { device ->
            device.address == targetAddress
        }

    }
    /**
     * GATT回调
     */
    private val gattCallback = object : BluetoothGattCallback() {
        /**
         * 连接状态变化回调
         */
        override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
            val device = gatt.device
            //gatt.requestMtu(158)
            when (newState) {
                BluetoothProfile.STATE_CONNECTED -> {
                    Timber.tag(TAG).w("设备已连接: ${device.address}")
                    
                    // 设置连接参数，请求更低延迟
                    setConnectionPriority(gatt, BluetoothGatt.CONNECTION_PRIORITY_HIGH)
                    
                    // 检查是否为已知设备（已发现过服务）
                    val isKnownDevice = discoveredServicesCache[device.address] == true
                    
                    if (isKnownDevice) {
                        // 对于已知设备，尝试直接使用缓存的服务
                        Timber.tag(TAG).w("设备已连接过，尝试直接验证服务: ${device.address}")
                        
                        try {
                            // 尝试获取服务，如果服务已缓存，不会触发服务发现
                            val services = gatt.services
                            if (services.isNotEmpty()) {
                                // 有服务缓存，验证必要服务和特征
                                if (validateRequiredServices(gatt)) {
                                    // 快速读取电池电量
                                    readBatteryLevel(gatt)
                                    
                                    // 发送连接成功事件
                                    coroutineScope.launch {
                                        deviceEventsFlow.emit(DeviceEvent.Connected(device))
                                        // 直接标记连接成功，不等待服务发现回调
                                        completeConnectionWithSuccess(device.address)
                                    }
                                    return
                                }
                            }
                        } catch (e: Exception) {
                            Timber.tag(TAG).w("使用缓存服务失败: ${e.message}")
                        }
                    }
                    
                    // 如果没有缓存或缓存无效，执行传统的服务发现
                    Timber.tag(TAG).w("开始发现服务: ${device.address}")
                    gatt.discoverServices()
                }

                BluetoothProfile.STATE_DISCONNECTED -> {
                    Timber.tag(TAG).w("设备已断开: ${device.address}")
                    // 从管理映射中移除，关闭GATT连接
                    deviceGattMap.remove(device.address)
                    gatt.close()

                    // 如果断开时正在等待连接结果，则标记为失败
                    completeConnectionWithFailure(device.address, "设备断开连接")

                    // 发送断开连接事件
                    coroutineScope.launch {
                        deviceEventsFlow.emit(DeviceEvent.Disconnected(device))
                    }
                }
            }
        }
        

        /**
         * 服务发现完成回调
         */
        override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
            val device = gatt.device
            val service = gatt.getService(BleConstants.SERVICE_UUID) ?: run {
                Timber.tag(TAG).e("发送鉴权状态失败: 找不到主服务")
                return
            }

            val readCharacteristic = service.getCharacteristic(BleConstants.CHARACTERISTIC_NOTIFY_UUID) ?: run {
                Timber.tag(TAG).e("发送鉴权状态失败: 找不到写入特征")
                return
            }
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // 验证设备服务和特征
                val isValidDevice = validateRequiredServices(gatt)
                Timber.tag(TAG).w("服务发现完成: ${device.address}, 验证结果: $isValidDevice")
                
                if (isValidDevice) {
                    // 标记设备已发现服务，用于优化重连
                    discoveredServicesCache[device.address] = true
                    
                    // 缓存服务特征映射
                    cacheDeviceCharacteristics(gatt)
                    


                    // 执行设备鉴权
                    coroutineScope.launch {
                        // 检查是否需要进行鉴权
                        val enableAuth =settingsRepository.enableAuthentication.first()
                        
                        if (enableAuth) {
                            // 开启了鉴权，进行设备鉴权
                            Timber.tag(TAG).w("鉴权已启用，开始设备鉴权: ${device.address}")
                            val authSuccess = authenticateDevice(device)
                            
                            if (authSuccess) {
                                // 鉴权成功，发送连接成功事件
                                deviceEventsFlow.emit(DeviceEvent.Connected(device))
                                deviceEventsFlow.emit(DeviceEvent.AuthSuccess(device))
                                // 标记连接成功
                                completeConnectionWithSuccess(device.address)
                                //延迟发送，首次连接蓝牙，需要延迟发送数据才能成功
                                Thread.sleep(DELAY_SEND)
                                readCharacteristicWithTimeout(gatt,readCharacteristic)
                                // 读取电池电量
                                readBatteryLevel(gatt)
                            } else {
                                // 鉴权失败，断开连接
                                Timber.tag(TAG).e("设备鉴权失败，断开连接: ${device.address}")
                                deviceEventsFlow.emit(DeviceEvent.AuthFailed(device, "设备鉴权失败"))

                                gatt.disconnect()
                                completeConnectionWithFailure(device.address, "设备鉴权失败")
                            }
                        } else {
                            // 未开启鉴权，直接标记连接成功
                            Timber.tag(TAG).w("鉴权已禁用，跳过设备鉴权: ${device.address}")
                            deviceEventsFlow.emit(DeviceEvent.Connected(device))
                            completeConnectionWithSuccess(device.address)
                            //延迟发送，首次连接蓝牙，需要延迟发送数据才能成功
                            Thread.sleep(DELAY_SEND)
                            readCharacteristicWithTimeout(gatt,readCharacteristic)
                            // 读取电池电量
                            readBatteryLevel(gatt)
                        }
                    }
                } else {
                    // 设备缺少必要服务，断开连接
                    Timber.tag(TAG).e("设备缺少必要的服务或特征: ${device.address}")
                    coroutineScope.launch {
                        deviceEventsFlow.emit(
                            DeviceEvent.ConnectionFailed(
                                device,
                                "设备缺少必要的服务或特征"
                            )
                        )
                    }

                    gatt.disconnect()
                    completeConnectionWithFailure(device.address, "设备缺少必要的服务或特征")
                }
            } else {
                Timber.tag(TAG).e("服务发现失败: $status")
                coroutineScope.launch {
                    deviceEventsFlow.emit(DeviceEvent.ConnectionFailed(device, "服务发现失败"))
                }

                completeConnectionWithFailure(device.address, "服务发现失败")
            }
        }

        /**
         * 描述符写入完成回调
         */
        override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
            if (descriptor.uuid == BleConstants.CLIENT_CHARACTERISTIC_CONFIG_UUID) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Timber.tag(TAG).w("通知描述符写入成功: ${descriptor.characteristic.uuid}")
                    // 通知配置成功，设备准备就绪
                    coroutineScope.launch {
                        deviceEventsFlow.emit(DeviceEvent.DeviceReady(gatt.device))
                    }
                } else {
                    Timber.tag(TAG).e("通知描述符写入失败: ${descriptor.characteristic.uuid}, 状态码: $status")
                }
            }
        }


        /**
         * 特征值变化回调（用于接收通知）
         */
        @Deprecated("Deprecated in Java")
        override fun onCharacteristicChanged(
            gatt: BluetoothGatt,
            characteristic: BluetoothGattCharacteristic
        ) {
            // 使用同步锁，确保多线程环境下的数据一致性
            synchronized(characteristicChangedLock) {
                when (characteristic.uuid) {
                    BleConstants.CHARACTERISTIC_NOTIFY_UUID -> {
                        val data = characteristic.value
                        if (data == null) {
                            Timber.tag(TAG).e("收到空数据包")
                            return
                        }

                        val threadID = Thread.currentThread().id
                        
                        // 计算数据包的唯一标识
                        val notificationKey = "${gatt.device.address}_${bytesToHex(data)}"
                        val currentTime = System.currentTimeMillis()
                        
                        // 检查是否是重复通知（100毫秒内收到完全相同的数据）
                        //val lastTime = lastProcessedNotification[notificationKey]
                        //if (lastTime != null && (currentTime - lastTime) < 100) {
                        //    Timber.tag(TAG).w("忽略可能的重复通知: ${bytesToHex(data)}, 距上次处理: ${currentTime - lastTime}ms")
                        //    return
                        //}
                        
                        // 记录数据包内容
                        Timber.tag(TAG).w("收到数据包: ${bytesToHex(data)}, 长度: ${data.size}, 线程：${threadID}")
                        
                        // 更新最近处理的通知记录
                        lastProcessedNotification[notificationKey] = currentTime
                        
                        // 清理过期的通知记录
                        clearExpiredNotifications(currentTime)

                        // 验证数据包格式
                        if (data.size >= 2) {
                            when (data[0]) {
                                BleConstants.HEADER_NOTIFICATION -> {
                                    // 处理按键通知
                                    if (data.size >= 4) { // 只检查长度
                                        val keyCode = data[1]
                                        Timber.tag(TAG).w("收到按键代码: 0x${keyCode.toUByte().toString(16)}")

                                        coroutineScope.launch {
                                            deviceEventsFlow.emit(DeviceEvent.ButtonPressed(gatt.device, keyCode))
                                        }
                                    }
                                }
                                BleConstants.HEADER_AUTH -> {
                                    // 处理鉴权响应
                                    handleAuthResponse(gatt, data)
                                }
                                else -> {
                                    Timber.tag(TAG).w("收到未知头部的数据包: 0x${data[0].toUByte().toString(16)}")
                                }
                            }
                        } else {
                            Timber.tag(TAG).w("收到的数据包格式不正确")
                        }
                    }
                    BleConstants.BATTERY_LEVEL_UUID -> {
                        val data = characteristic.value
                        if (data == null) {
                            Timber.tag(TAG).e("收到空数据包")
                            return
                        }
                    }
                }
            }
        }

        /**
         * 特征读取完成回调
         */
        @Deprecated("Deprecated in Java")
        override fun onCharacteristicRead(
            gatt: BluetoothGatt,
            characteristic: BluetoothGattCharacteristic,
            status: Int
        ) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                when (characteristic.uuid) {
                    BleConstants.BATTERY_LEVEL_UUID -> {
                        val batteryLevel = characteristic.value[0].toInt() and 0xFF
                        Timber.tag(TAG).w("设备电量: ${batteryLevel}%")
                        coroutineScope.launch {
                            deviceEventsFlow.emit(
                                DeviceEvent.BatteryLevelChanged(gatt.device, batteryLevel)
                            )
                        }
                    }
                    BleConstants.CHARACTERISTIC_NOTIFY_UUID -> {

                        val uuid = characteristic.uuid.toString()
                        writeCallbacks[uuid]?.let { deferred ->
                            if (!deferred.isCompleted) {
                                deferred.complete(status == BluetoothGatt.GATT_SUCCESS)
                            }
                            writeCallbacks.remove(uuid)
                        }

                        val readVules = BleAuthUtils.byteArrayToHexString(characteristic.value)

                        Timber.tag(TAG).e("读取设备Read反馈=${readVules}")
                        coroutineScope.launch {
                            deviceEventsFlow.emit(
                                DeviceEvent.SetReadVules(gatt.device, readVules)
                            )
                        }
                    }
                }
            }
        }

        /**
         * 特征写入完成回调
         */
        @Deprecated("Deprecated in Java")
        override fun onCharacteristicWrite(
            gatt: BluetoothGatt,
            characteristic: BluetoothGattCharacteristic,
            status: Int
        ) {
            val uuid = characteristic.uuid.toString()
            Timber.tag(TAG).w("特征写入完成: $uuid, 状态: $status")
            
            writeCallbacks[uuid]?.let { deferred ->
                if (!deferred.isCompleted) {
                    deferred.complete(status == BluetoothGatt.GATT_SUCCESS)
                }
                writeCallbacks.remove(uuid)
            }
        }

//        override fun onMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) {
//            super.onMtuChanged(gatt, mtu, status)
//            Timber.tag(TAG).w("ATT MTU changed to $mtu, 状态: ${status == BluetoothGatt.GATT_SUCCESS}")
//        }
    }

    /**
     * 将字节数组转换为十六进制字符串（用于日志调试）
     */
    private fun bytesToHex(bytes: ByteArray): String {
        val hexChars = "0123456789ABCDEF"
        val result = StringBuilder(bytes.size * 3)
        for (b in bytes) {
            result.append(hexChars[b.toInt() shr 4 and 0xF])
            result.append(hexChars[b.toInt() and 0xF])
            result.append(' ')
        }
        return result.toString().trim()
    }

    /**
     * 验证设备是否具有所有必需的服务和特征
     * @param gatt 蓝牙GATT连接
     * @return 验证成功返回true，否则返回false
     */
    private fun validateRequiredServices(gatt: BluetoothGatt): Boolean {
        // 1. 检查主服务
        val mainService = gatt.getService(BleConstants.SERVICE_UUID) ?: run {
            Timber.tag(TAG).e("设备缺少主服务: ${gatt.device.address}")
            return false
        }

        // 2. 检查写入特征
        val writeCharacteristic = mainService.getCharacteristic(BleConstants.CHARACTERISTIC_WRITE_UUID) ?: run {
            Timber.tag(TAG).e("设备缺少写入特征: ${gatt.device.address}")
            return false
        }

        // 3. 检查通知特征
        val notifyCharacteristic = mainService.getCharacteristic(BleConstants.CHARACTERISTIC_NOTIFY_UUID) ?: run {
            Timber.tag(TAG).e("设备缺少通知特征: ${gatt.device.address}")
            return false
        }
        
        // 4. 正确配置通知特征
        if (!enableCharacteristicNotification(gatt, notifyCharacteristic)) {
            Timber.tag(TAG).e("无法启用通知特征: ${gatt.device.address}")
            return false
        }

        // 5. 检查电池服务（可选）
        val batteryService = gatt.getService(BleConstants.BATTERY_SERVICE_UUID)
        if (batteryService != null) {
            val batteryCharacteristic = batteryService.getCharacteristic(BleConstants.BATTERY_LEVEL_UUID)
            if (batteryCharacteristic == null) {

                Timber.tag(TAG).w("设备有电池服务但缺少电池电量特征: ${gatt.device.address}")
                // 电池特征是可选的，不影响连接结果
            }else{

                val descriptor = batteryCharacteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"))
                if (descriptor != null) {
                    Timber.tag(TAG).w("Client Characteristic Configuration descriptor not found!")
//                    if (!enableCharacteristicNotification(gatt, batteryCharacteristic)) {
//                    Timber.tag(TAG).e("无法启用电池服务通知特征: ${gatt.device.address}")
//                    return false
//                }
                }

            }
        } else {
            Timber.tag(TAG).w("设备缺少电池服务: ${gatt.device.address}")
            // 电池服务是可选的，不影响连接结果
        }

        Timber.tag(TAG).w("设备验证成功: ${gatt.device.address}")
        return true
    }

    /**
     * 启用特征的通知功能
     * @param gatt GATT连接
     * @param characteristic 需要启用通知的特征
     * @return 成功返回true，否则返回false
     */
    private fun enableCharacteristicNotification(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic): Boolean {
        // 1. 启用本地通知
        if (!gatt.setCharacteristicNotification(characteristic, true)) {
            Timber.tag(TAG).e("无法启用特征通知: ${characteristic.uuid}")
            return false
        }
        
        // 2. 获取并配置客户端特征配置描述符(CCCD)
        val descriptor = characteristic.getDescriptor(BleConstants.CLIENT_CHARACTERISTIC_CONFIG_UUID) ?: run {
            Timber.tag(TAG).e("找不到通知描述符: ${characteristic.uuid}")
            return false
        }
        
        // 3. 写入描述符，启用通知
        descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
        if (!gatt.writeDescriptor(descriptor)) {
            Timber.tag(TAG).e("写入通知描述符失败: ${characteristic.uuid}")
            return false
        }
        
        Timber.tag(TAG).w("已请求启用通知特征: ${characteristic.uuid}")
        return true
    }

    /**
     * 完成连接并标记为成功
     * @param deviceAddress 设备MAC地址
     */
    private fun completeConnectionWithSuccess(deviceAddress: String) {
        connectionResults[deviceAddress]?.let { deferred ->
            if (!deferred.isCompleted) {
                deferred.complete(true)
                Timber.tag(TAG).w("连接完成并标记为成功: $deviceAddress")
            }
            connectionResults.remove(deviceAddress)
        }
    }

    /**
     * 完成连接并标记为失败
     * @param deviceAddress 设备MAC地址
     * @param reason 失败原因
     */
    private fun completeConnectionWithFailure(deviceAddress: String, reason: String) {
        connectionResults[deviceAddress]?.let { deferred ->
            if (!deferred.isCompleted) {
                deferred.complete(false)
                Timber.tag(TAG).e("连接失败: $deviceAddress, 原因: $reason")
            }
            connectionResults.remove(deviceAddress)
        }
    }

    /**
     * 读取设备电池电量
     * @param gatt 蓝牙GATT连接
     */
    private fun readBatteryLevel(gatt: BluetoothGatt) {
        val batteryService = gatt.getService(BleConstants.BATTERY_SERVICE_UUID) ?: run {
            Timber.tag(TAG).w("无法读取电池电量: 设备缺少电池服务")
            return
        }
        
        val batteryCharacteristic = batteryService.getCharacteristic(BleConstants.BATTERY_LEVEL_UUID) ?: run {
            Timber.tag(TAG).w("无法读取电池电量: 设备缺少电池电量特征")
            return
        }

        gatt.readCharacteristic(batteryCharacteristic)
    }

    /**
     * 带超时保护的写入特征
     * @param gatt GATT连接
     * @param characteristic 要写入的特征
     * @param value 写入的数据
     * @param timeoutMs 超时时间（毫秒）
     * @return 写入成功返回true，否则返回false
     */
    private suspend fun writeCharacteristicWithTimeout(
        gatt: BluetoothGatt,
        characteristic: BluetoothGattCharacteristic,
        value: ByteArray,
        timeoutMs: Long = DELAY_TIMEOUT
    ): Boolean = withContext(Dispatchers.IO) {
        val uuid = characteristic.uuid.toString()
        val result = CompletableDeferred<Boolean>()
        
        // 保存回调
        writeCallbacks[uuid] = result
        
        // 设置超时
        val timeoutJob = coroutineScope.launch {
            delay(timeoutMs)
            if (!result.isCompleted) {
                result.complete(false)
                writeCallbacks.remove(uuid)
                Timber.tag(TAG).e("写入特征超时: $uuid")
            }
        }
        // 执行写入
        characteristic.value = value
        val writeStarted = gatt.writeCharacteristic(characteristic)
        
        if (!writeStarted) {
            timeoutJob.cancel()
            writeCallbacks.remove(uuid)
            Timber.tag(TAG).e("启动写入失败: $uuid")
            return@withContext false
        }else{
            Timber.tag(TAG).e("启动写入成功: $uuid")
        }
        
        // 等待写入完成或超时
        val success = result.await()
        timeoutJob.cancel()
        
        return@withContext success
    }


    /**
     * 带超时保护的读取特征
     * @param gatt GATT连接
     * @param characteristic 要写入的特征
     * @param timeoutMs 超时时间（毫秒）
     * @return 写入成功返回true，否则返回false
     */
    private suspend fun readCharacteristicWithTimeout(
        gatt: BluetoothGatt,
        characteristic: BluetoothGattCharacteristic,
        timeoutMs: Long = DELAY_TIMEOUT
    ): Boolean = withContext(Dispatchers.IO) {
        val uuid = characteristic.uuid.toString()
        val result = CompletableDeferred<Boolean>()

        // 保存回调
        writeCallbacks[uuid] = result

        // 设置超时
        val timeoutJob = coroutineScope.launch {
            delay(timeoutMs)
            if (!result.isCompleted) {
                result.complete(false)
                writeCallbacks.remove(uuid)
                Timber.tag(TAG).e("读取特征超时: $uuid")
            }
        }

        val writeStarted = gatt.readCharacteristic(characteristic)

        if (!writeStarted) {
            timeoutJob.cancel()
            writeCallbacks.remove(uuid)
            Timber.tag(TAG).e("启动读取失败: $uuid")
            return@withContext false
        }else{
            Timber.tag(TAG).e("启动读取成功: $uuid")
        }

        // 等待写入完成或超时
        val success = result.await()
        timeoutJob.cancel()

        return@withContext success
    }
    
    /**
     * 发送命令到设备
     * @param device 蓝牙设备
     * @param header 命令头
     * @param instruction 指令类型
     * @param value1 参数1
     * @param value2 参数2
     * @param value3 参数3
     * @return 发送成功返回true，否则返回false
     */
    private suspend fun sendCommand(
        device: BluetoothDevice,
        header: Byte,
        instruction: Byte,
        value1: Byte,
        value2: Byte,
        value3: Byte,
    ): Boolean = withContext(Dispatchers.IO) {
        val gatt = deviceGattMap[device.address] ?: run {
            Timber.tag(TAG).e("发送命令失败: 设备未连接 ${device.address}")
            return@withContext false
        }
        
        val service = gatt.getService(BleConstants.SERVICE_UUID) ?: run {
            Timber.tag(TAG).e("发送命令失败: 找不到主服务 ${device.address}")
            return@withContext false
        }
        
        val characteristic = service.getCharacteristic(BleConstants.CHARACTERISTIC_WRITE_UUID) ?: run {
            Timber.tag(TAG).e("发送命令失败: 找不到写入特征 ${device.address}")
            return@withContext false
        }

        // 构建命令数据
        val command = byteArrayOf(header, instruction, value1, value2, value3)
        Timber.tag(TAG).w("发送命令: ${bytesToHex(command)} 到设备 ${device.address}")

        // 使用带超时的写入
        return@withContext writeCharacteristicWithTimeout(gatt, characteristic, command)
    }


    private suspend fun sendCommand2(
        address: String,
        header: Byte,
        instruction: Byte,
        value1: Byte,
        value2: Byte,
        value3: Byte,
    ): Boolean = withContext(Dispatchers.IO) {
        val gatt = deviceGattMap[address] ?: run {
            Timber.tag(TAG).e("发送命令失败: 设备未连接 ${address}")
            return@withContext false
        }

        val service = gatt.getService(BleConstants.SERVICE_UUID) ?: run {
            Timber.tag(TAG).e("发送命令失败: 找不到主服务 ${address}")
            return@withContext false
        }

        val characteristic = service.getCharacteristic(BleConstants.CHARACTERISTIC_WRITE_UUID) ?: run {
            Timber.tag(TAG).e("发送命令失败: 找不到写入特征 ${address}")
            return@withContext false
        }

        // 构建命令数据
        val command = byteArrayOf(header, instruction, value1, value2, value3)
        Timber.tag(TAG).w("发送命令: ${bytesToHex(command)} 到设备 ${address}")

        // 使用带超时的写入
        return@withContext writeCharacteristicWithTimeout(gatt, characteristic, command)
    }


    /**
     * 设置设备工作状态下的LED颜色
     * @param device 蓝牙设备
     * @param r 红色分量 (0-255)
     * @param g 绿色分量 (0-255)
     * @param b 蓝色分量 (0-255)
     * @return 设置成功返回true，否则返回false
     */
    override suspend fun setWorkingLedColor(
        device: BluetoothDevice,
        r: Int,
        g: Int,
        b: Int
    ): Boolean = sendCommand(
        device,
        BleConstants.HEADER_CONTROL,
        BleConstants.Instruction.BACKLIGHT_IN_WORKING,
        r.toByte(),
        g.toByte(),
        b.toByte(),
    )

    override suspend fun setWorkingLedColor2(
        device: String,
        r: Int,
        g: Int,
        b: Int
    ): Boolean = sendCommand2(
        device,
        BleConstants.HEADER_CONTROL,
        BleConstants.Instruction.BACKLIGHT_IN_WORKING,
        r.toByte(),
        g.toByte(),
        b.toByte(),
    )

    override suspend fun setPreventAccid(
        device: String,
        pA: Int
    ): Boolean = sendCommand2(
        device,
        BleConstants.HEADER_CONTROL,
        BleConstants.Instruction.KNOB_ANTI_MISOPERATION,
        pA.toByte(),
        0,
        0,
    )

    /**
     * 设置设备重连状态下的LED颜色
     * @param device 蓝牙设备
     * @param r 红色分量 (0-255)
     * @param g 绿色分量 (0-255)
     * @param b 蓝色分量 (0-255)
     * @return 设置成功返回true，否则返回false
     */
    override suspend fun setReconnectingLedColor(
        device: BluetoothDevice,
        r: Int,
        g: Int,
        b: Int
    ): Boolean = sendCommand(
        device,
        BleConstants.HEADER_CONTROL,
        BleConstants.Instruction.BACKLIGHT_IN_WAITING_RECONNECTION,
        r.toByte(),
        g.toByte(),
        b.toByte(),
    )

    /**
     * 设置设备防误触模式
     * @param device 蓝牙设备
     * @param enabled 是否启用防误触
     * @return 设置成功返回true，否则返回false
     */
    override suspend fun setAntiMisoperation(
        device: BluetoothDevice,
        enabled: Boolean
    ): Boolean = sendCommand(
        device,
        BleConstants.HEADER_CONTROL,
        BleConstants.Instruction.KNOB_ANTI_MISOPERATION,
        if (enabled) 0x01 else 0x00,
        0x00,
        0x00,
    )

    /**
     * 断开现有的设备连接
     * @param deviceAddress 设备MAC地址
     */
    private fun disconnectExistingConnection(deviceAddress: String) {
        val existingGatt = deviceGattMap[deviceAddress]
        if (existingGatt != null) {
            Timber.tag(TAG).w("断开现有连接: $deviceAddress")
            closeGattConnection(existingGatt)
            deviceGattMap.remove(deviceAddress)
        }
    }

    /**
     * 关闭GATT连接并释放资源
     * @param gatt GATT连接
     */
    private fun closeGattConnection(gatt: BluetoothGatt) {
        try {
            // 先断开连接
            gatt.disconnect()
            
            // 等待一段时间确保断开
            Thread.sleep(200)
            
            // 关闭GATT
            gatt.close()
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "关闭GATT连接时出错: ${gatt.device.address}")
        }
    }

    /**
     * 检查是否有蓝牙权限
     * @param permissionType 权限类型，"scan"表示扫描权限，其他值表示连接权限
     * @return 有权限返回true，否则返回false
     */
    private fun hasBluetoothPermission(permissionType: String = "connect"): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12及以上版本需要特定蓝牙权限
            val permission = when (permissionType) {
                "scan" -> Manifest.permission.BLUETOOTH_SCAN
                else -> Manifest.permission.BLUETOOTH_CONNECT
            }
            ActivityCompat.checkSelfPermission(
                appContext,
                permission
            ) == PackageManager.PERMISSION_GRANTED
        } else {
            // 旧版本Android使用传统蓝牙权限
            ActivityCompat.checkSelfPermission(
                appContext,
                Manifest.permission.BLUETOOTH
            ) == PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(
                        appContext,
                        Manifest.permission.BLUETOOTH_ADMIN
                    ) == PackageManager.PERMISSION_GRANTED
        }
    }

    /**
     * 设置连接优先级
     * @param gatt GATT连接
     * @param priority 优先级，如CONNECTION_PRIORITY_HIGH
     */
    private fun setConnectionPriority(gatt: BluetoothGatt, priority: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                val success = gatt.requestConnectionPriority(priority)
                if (success) {
                    Timber.tag(TAG).w("设置连接优先级成功: ${gatt.device.address}, 优先级=$priority")
                } else {
                    Timber.tag(TAG).w("设置连接优先级失败: ${gatt.device.address}")
                }
            } catch (e: Exception) {
                Timber.tag(TAG).e(e, "设置连接优先级时出错: ${gatt.device.address}")
            }
        }
    }

    /**
     * 缓存设备特征映射
     */
    private fun cacheDeviceCharacteristics(gatt: BluetoothGatt) {
        try {
            val characteristicMap = mutableMapOf<UUID, BluetoothGattCharacteristic>()
            
            // 获取所有服务
            for (service in gatt.services) {
                // 获取服务中的所有特征
                for (characteristic in service.characteristics) {
                    characteristicMap[characteristic.uuid] = characteristic
                }
            }
            
            // 存储特征映射
            deviceCharacteristics[gatt.device.address] = characteristicMap
            Timber.tag(TAG).w("已缓存设备特征映射: ${gatt.device.address}, 特征数量=${characteristicMap.size}")
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "缓存设备特征时出错: ${gatt.device.address}")
        }
    }

    /**
     * 对设备进行鉴权
     * @param device 蓝牙设备
     * @return 鉴权成功返回true，否则返回false
     */
    override suspend fun authenticateDevice(device: BluetoothDevice): Boolean = withContext(Dispatchers.IO) {
        try {
            Timber.tag(TAG).w("开始对设备进行鉴权: ${device.address}")
            
            // 获取设备GATT连接
            val gatt = deviceGattMap[device.address] ?: run {
                Timber.tag(TAG).e("鉴权失败: 找不到设备的GATT连接")
                return@withContext false
            }
            
            // 获取主服务
            val service = gatt.getService(BleConstants.SERVICE_UUID) ?: run {
                Timber.tag(TAG).e("鉴权失败: 找不到主服务")
                return@withContext false
            }
            
            // 获取写入特征
            val writeCharacteristic = service.getCharacteristic(BleConstants.CHARACTERISTIC_WRITE_UUID) ?: run {
                Timber.tag(TAG).e("鉴权失败: 找不到写入特征")
                return@withContext false
            }
            
            // 创建异步结果
            val authResult = CompletableDeferred<Boolean>()
            authenticationResults[device.address] = authResult
            
            // 生成随机盐值
            val hostSalt =BleAuthUtils.generateRandomSalt(BleConstants.Auth.SALT_LENGTH) //byteArrayOf(0x11,0x22,0x33,0x44,0x55,0x66,0x77, 0x88.toByte())
            
            // 存储鉴权信息
            authenticationData[device.address] = AuthData(hostSalt = hostSalt)

            
            // 构建鉴权请求命令
            val authRequest = ByteArray(2 + BleConstants.Auth.SALT_LENGTH)
            authRequest[0] = BleConstants.HEADER_AUTH
            authRequest[1] = BleConstants.AuthInstruction.AUTH_REQUEST
            System.arraycopy(hostSalt, 0, authRequest, 2, hostSalt.size)


            Timber.tag(TAG).w("发送鉴权请求: ${BleAuthUtils.byteArrayToHexString(authRequest)}")

            //延迟发送，首次连接蓝牙，需要延迟发送数据才能成功
            Thread.sleep(DELAY_SEND)

            // 发送鉴权请求
            val writeSuccess = writeCharacteristicWithTimeout(gatt, writeCharacteristic, authRequest)
            if (!writeSuccess) {
                Timber.tag(TAG).e("鉴权失败: 发送鉴权请求失败")
                authenticationResults.remove(device.address)
                return@withContext false
            }

            // 等待鉴权响应，设置5秒超时
            var authenticated = false
            try {
                authenticated = withTimeout(WAIT_TO) {
                    authResult.await()
                }
            } catch (e: TimeoutCancellationException) {
                Timber.tag(TAG).e("鉴权超时")
                authenticated = false
            }


            // 清理鉴权数据
            authenticationResults.remove(device.address)
            
            if (authenticated) {
                Timber.tag(TAG).w("设备鉴权成功: ${device.address}")
            } else {
                Timber.tag(TAG).e("设备鉴权失败: ${device.address}")
            }
            
            return@withContext authenticated
            
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "鉴权过程发生异常")
            return@withContext false
        }
    }
    
    /**
     * 处理设备的鉴权响应
     * @param gatt 设备GATT连接
     * @param data 响应数据
     */
    private fun handleAuthResponse(gatt: BluetoothGatt, data: ByteArray) {
        val device = gatt.device



        if (data.size < 3) {
            Timber.tag(TAG).e("鉴权响应数据长度不足")
            return
        }
        
        if (data[1] == BleConstants.AuthInstruction.AUTH_RESPONSE) {
            // 处理AUTH_RESPONSE
            if (data.size < 2 + BleConstants.Auth.SALT_LENGTH + BleConstants.Auth.PUBLIC_ADDR_LENGTH + BleConstants.Auth.AUTH_DATA_LENGTH) {
                Timber.tag(TAG).e("鉴权响应数据长度不足: ${data.size} 字节")
                completeAuthentication(device.address, false)
                return
            }
            
            try {
                // 获取灵动贴Salt
                val deviceSalt = data.copyOfRange(2, 2 + BleConstants.Auth.SALT_LENGTH)
                
                // 获取加密的PublicAddr
                val encryptedAddr = data.copyOfRange(
                    2 + BleConstants.Auth.SALT_LENGTH, 
                    2 + BleConstants.Auth.SALT_LENGTH + BleConstants.Auth.PUBLIC_ADDR_LENGTH
                )
                
                // 获取认证数据
                val authData = data.copyOfRange(
                    2 + BleConstants.Auth.SALT_LENGTH + BleConstants.Auth.PUBLIC_ADDR_LENGTH,
                    2 + BleConstants.Auth.SALT_LENGTH + BleConstants.Auth.PUBLIC_ADDR_LENGTH + BleConstants.Auth.AUTH_DATA_LENGTH
                )
                
                // 获取之前存储的车机Salt
                val hostSalt = authenticationData[device.address]?.hostSalt ?: run {
                    Timber.tag(TAG).e("找不到车机Salt")
                    completeAuthentication(device.address, false)
                    return
                }
                
                // 生成密钥材料
                val (iv, key) = BleAuthUtils.generateKeyMaterial(
                    hostSalt, 
                    deviceSalt, 
                    BleConstants.Auth.AUTH_LABEL
                )



                // 1. 验证PublicAddr
                val decryptedAddr = BleAuthUtils.aesDecrypt(encryptedAddr, key, iv)

                val deviceName = device.address ?: ""

                // 使用补0的设备名称进行比对
                val expectedAddr = BleAuthUtils.padDeviceName2(deviceName.replace(":",""), BleConstants.Auth.PUBLIC_ADDR_LENGTH)

                Timber.tag(TAG).e("接收0402数据=${BleAuthUtils.byteArrayToHexString(data)}")
                Timber.tag(TAG).e("获取加密的PublicAddr=${BleAuthUtils.byteArrayToHexString(encryptedAddr)}")
                Timber.tag(TAG).e("车机Salt=${BleAuthUtils.byteArrayToHexString(hostSalt)}")
                Timber.tag(TAG).e("灵动贴Salt=${BleAuthUtils.byteArrayToHexString(deviceSalt)}")
                Timber.tag(TAG).e("生成密钥材料: iv=${BleAuthUtils.byteArrayToHexString(iv)}, key=${BleAuthUtils.byteArrayToHexString(key)}")
                Timber.tag(TAG).e("车机Addr=${BleAuthUtils.byteArrayToHexString(expectedAddr.reversedArray())}")
                Timber.tag(TAG).e("解密的PublicAddr=${BleAuthUtils.byteArrayToHexString(decryptedAddr)}")

                // 检查PublicAddr是否匹配
                val addrMatched = decryptedAddr.contentEquals(expectedAddr.reversedArray())
                if (!addrMatched) {
                    Timber.tag(TAG).e("PublicAddr不匹配: 期望=${BleAuthUtils.byteArrayToHexString(expectedAddr.reversedArray())}, 实际=${BleAuthUtils.byteArrayToHexString(decryptedAddr)}")
                    sendAuthStatus(gatt, false)
                    completeAuthentication(device.address, false)
                    return
                }
                
                // 2. 验证认证数据
                val expectedRawData = BleAuthUtils.generateRawAuthData(hostSalt, deviceSalt).copyOfRange(0,BleConstants.Auth.PUBLIC_ADDR_LENGTH).reversedArray()
                val decryptedAuthData = BleAuthUtils.aesDecrypt(authData, key, iv)

                // Timber.tag(TAG).e("expectedRawData=${BleAuthUtils.byteArrayToHexString(expectedRawData)}")
                // Timber.tag(TAG).e("decryptedAuthData=${BleAuthUtils.byteArrayToHexString(decryptedAuthData)}")


                // 检查认证数据是否匹配
                val dataMatched = decryptedAuthData.contentEquals(expectedRawData)

                if (!dataMatched) {
                    Timber.tag(TAG).e("认证数据不匹配")
                    sendAuthStatus(gatt, false)
                    completeAuthentication(device.address, false)
                    return
                }
                
                // 鉴权成功，发送成功状态
                Timber.tag(TAG).w("设备鉴权验证成功")
                
                // 存储新的鉴权信息（包含设备Salt）
                authenticationData[device.address] = AuthData(
                    hostSalt = hostSalt,
                    deviceSalt = deviceSalt,
                    iv = iv,
                    key = key
                )
                
                // 发送鉴权成功响应
                sendAuthStatus(gatt, true)
                
                // 完成鉴权
                completeAuthentication(device.address, true)
                
            } catch (e: Exception) {
                Timber.tag(TAG).e(e, "处理鉴权响应时发生异常")
                sendAuthStatus(gatt, false)
                completeAuthentication(device.address, false)
            }
        } else {
            Timber.tag(TAG).e("收到未知的鉴权指令: ${data[1]}")
            completeAuthentication(device.address, false)
        }
    }
    
    /**
     * 发送鉴权状态给设备
     * @param gatt GATT连接
     * @param success 是否鉴权成功
     */
    private fun sendAuthStatus(gatt: BluetoothGatt, success: Boolean) {
        // 获取写入特征
        val service = gatt.getService(BleConstants.SERVICE_UUID) ?: run {
            Timber.tag(TAG).e("发送鉴权状态失败: 找不到主服务")
            return
        }
        
        val writeCharacteristic = service.getCharacteristic(BleConstants.CHARACTERISTIC_WRITE_UUID) ?: run {
            Timber.tag(TAG).e("发送鉴权状态失败: 找不到写入特征")
            return
        }
        
        // 构建状态响应
        val statusCode = if (success) BleConstants.AuthStatus.AUTH_SUCCESS else BleConstants.AuthStatus.AUTH_FAILED
        val statusResponse = ByteArray(4)
        statusResponse[0] = BleConstants.HEADER_AUTH
        statusResponse[1] = BleConstants.AuthInstruction.AUTH_STATUS_RESPONSE
        statusResponse[2] = (statusCode and 0xFF).toByte()
        statusResponse[3] = (statusCode.toInt() shr 8 and 0xFF).toByte()

        Timber.tag(TAG).w("发送鉴权状态: ${if (success) "成功" else "失败"}")
        
        // 发送状态响应
        coroutineScope.launch(Dispatchers.IO) {
            writeCharacteristicWithTimeout(gatt, writeCharacteristic, statusResponse)
        }
    }
    
    /**
     * 完成鉴权并通知结果
     * @param deviceAddress 设备地址
     * @param success 是否鉴权成功
     */
    private fun completeAuthentication(deviceAddress: String, success: Boolean) {
        authenticationResults[deviceAddress]?.let { deferred ->
            if (!deferred.isCompleted) {
                deferred.complete(success)
                Timber.tag(TAG).w("鉴权完成: ${deviceAddress}, 结果: ${if (success) "成功" else "失败"}")
            }
        }
    }
    
    /**
     * 鉴权数据类
     */
    private data class AuthData(
        val hostSalt: ByteArray,          // 车机随机数
        val deviceSalt: ByteArray? = null, // 灵动贴随机数
        val iv: ByteArray? = null,        // 初始化向量
        val key: ByteArray? = null        // AES密钥
    ) {
        override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (other !is AuthData) return false
            
            if (!hostSalt.contentEquals(other.hostSalt)) return false
            if (deviceSalt != null) {
                if (other.deviceSalt == null) return false
                if (!deviceSalt.contentEquals(other.deviceSalt)) return false
            } else if (other.deviceSalt != null) return false
            if (iv != null) {
                if (other.iv == null) return false
                if (!iv.contentEquals(other.iv)) return false
            } else if (other.iv != null) return false
            if (key != null) {
                if (other.key == null) return false
                if (!key.contentEquals(other.key)) return false
            } else if (other.key != null) return false
            
            return true
        }
        
        override fun hashCode(): Int {
            var result = hostSalt.contentHashCode()
            result = 31 * result + (deviceSalt?.contentHashCode() ?: 0)
            result = 31 * result + (iv?.contentHashCode() ?: 0)
            result = 31 * result + (key?.contentHashCode() ?: 0)
            return result
        }
    }

    /**
     * 清理过期的通知记录
     */
    private fun clearExpiredNotifications(currentTime: Long) {
        // 只保留最近500毫秒内的通知记录
        if (lastProcessedNotification.size > 20) {
            val keysToRemove = lastProcessedNotification.entries
                .filter { (currentTime - it.value) > 500 }
                .map { it.key }
            
            keysToRemove.forEach { lastProcessedNotification.remove(it) }
        }
    }


    /**
     */
    override suspend fun getBleDevices(): List<BluetoothDevice> = withContext(Dispatchers.IO) {

        return@withContext bluetoothManager.getConnectedDevices(android.bluetooth.BluetoothProfile.GATT)

    }
}